package com.system.healthproject.controller;

import com.system.healthproject.bean.FileBean;
import com.system.healthproject.common.ApiResult;
import io.swagger.annotations.Api;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Api(value = "文件上传",tags = "公共-文件上传API")
@RestController
@RequestMapping("/file")
@Validated
public class FileController {

    @RequestMapping(value="/upload", method = RequestMethod.POST,headers = "content-type=multipart/form-data")
    public ApiResult fileUpload(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request) throws IOException {
        if (multipartFile.isEmpty()) {
            return ApiResult.failure("参数不能为空");
        } else {
            System.out.println("开始上传");
            String uploadPath = request.getServletContext().getRealPath("")
                    + File.separator+ "upload" + File.separator;
            File file = new File(uploadPath);
            if(!file.exists()){
                file.mkdirs();
            }
            String fileName = multipartFile.getOriginalFilename();
            String extension = FilenameUtils.getExtension(fileName);
            String newFileStr=
                    UUID.randomUUID().toString().replaceAll("_","");
            fileName = newFileStr + "." + extension;
            File newFile = new File(uploadPath + fileName);
            System.out.println("newFile=" + newFile);
            FileCopyUtils.copy(multipartFile.getBytes(), newFile);
            String relativePath = "http://zhoudw.vip/healthproject/upload/" + fileName;
            return ApiResult.success(relativePath);
        }
    }

}
